<?php

namespace App\Http\Controllers\App\V1;

use Carbon\Carbon;
use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;

class BadgeController extends BaseController
{
    public function show()
    {
        //我所拥有的徽章
        $user_badge = app('repo_badge')->getUserBadgeList(UID);

        //所有徽章列表
        $badge_list = app('repo_badge')->getBadgeList();
        foreach ($badge_list as $key => &$value) {
            if (in_array($value->id, $user_badge)) {
                $value->owned = 1;
            } else {
                $value->owned = 0;
            }
        }

        //所有已领取的奖励
        $exchange_list = app('repo_badge')->getUserExchangeList(UID);

        //我的徽章数量
        $count = $user_badge ? count($user_badge) : 0;

        return Response::sendData(['total' => $count, 'exchange_list' => $exchange_list, 'list' => $badge_list]);
    }

    public function receive(Request $request)
    {
        $goods_id = $request->input('goods_id');
        $badge_config = app('model_config')->getValue('BADGE_PRIZE');
        $goods_id_1 = $badge_config['goods_id_1'] ?? 0;
        $goods_id_2 = $badge_config['goods_id_2'] ?? 0;
        $goods_id_3 = $badge_config['goods_id_3'] ?? 0;
        $goods_list = [
            1 => ['product_id' => $goods_id_1, 'name' => '星梦之旅15天', 'type' => 'head', 'number' => 3, 'days' => 15],
            2 => ['product_id' => $goods_id_2, 'name' => '星梦之旅7天', 'type' => 'join', 'number' => 5, 'days' => 7],
            3 => ['product_id' => $goods_id_3, 'name' => '鲸奇一梦7天', 'type' => 'ride', 'number' => 7, 'days' => 7],
            4 => ['product_id' => 0, 'name' => '终极大奖', 'type' => 'final', 'number' => 10, 'days' => 0],
        ];
        if (!isset($goods_list[$goods_id]) || $goods_list[$goods_id] <= 0) {
            throw new BasicException(10004);
        }
        $goods = $goods_list[$goods_id];

        //获取我的总徽章数量
        $total = app('repo_badge')->getUserBadgeCount(UID);
        if ($total < $goods['number']) {
            throw new BasicException(20100);
        }

        //判断是否已领取过奖励
        $check = app('repo_badge')->checkUserExchange(UID, $goods_id);
        if ($check) {
            throw new BasicException(20101);
        }

        if ($goods['type'] != 'final') {
            //赠送个性商城礼物
            app('model_mall_orders')->give($goods['product_id'], UID, $goods['days']);
        }

        app('model_badge_exchange')->insert(
            [
                'user_id'    => UID,
                'goods_id'   => $goods_id,
                'goods_name' => $goods['name'],
                'number'     => $goods['number'],
                'add_time'   => Carbon::now()->timestamp
            ]
        );
        return Response::sendData('success');
    }
}
